package com.bookcycle.panda.webfront.controller;

import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.annotation.Action;
import com.baomidou.kisso.annotation.Login;
import com.baomidou.kisso.security.token.SSOToken;
import com.baomidou.kisso.web.waf.request.WafRequestWrapper;

import com.bookcycle.panda.webfront.constant.URLConstant;
import com.bookcycle.panda.webfront.doo.UserDO;

import com.bookcycle.panda.webfront.vo.MyOrderVo;
import com.bookcycle.panda.webfront.vo.UserVO;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * tets
 * @author Mason
 * @date 2018/3/6
 */
@Controller
public class UserController extends BaseController{
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    private final String LOGIN_SUCCESS="登录成功";
    private final String REGISTER_SUCCESS="注册成功";
    private final String UPDATE_SUCCESS="修改成功";
    private final String USER_SERVICE_ERROR="用户服务器错误";
    private final String BAD_PARAM="账号、密码不符合要求";
    private final String ACCOUNT_EXIST="账号已经存在";
    private final String ACCOUNT_NOT_EXIST="账号不存在";
    private final String ERROR_UNKNOWN="未知错误";
    private final String PASSWORD_NOT_EQUAL="密码不一致";
    private final String NO_AUTHORITY="没有权限";

    /**
     * 显示个人信息
     * @param model
     * @return
     */
    @RequestMapping(value = "showUser",method = RequestMethod.GET)
    public String showUser(Model model){
        SSOToken ssoToken=SSOHelper.getSSOToken(request);
        String userId=ssoToken.getId();
        RestTemplate restTemplate=new RestTemplate();
        MultiValueMap multiValueMap=new LinkedMultiValueMap();
        multiValueMap.add("userId",userId);
        try{
            ResponseEntity<UserDO> responseEntity=restTemplate.postForEntity(URLConstant.URL_GET_USER_BY_ID,multiValueMap,UserDO.class);
            UserDO userDO=responseEntity.getBody();
            UserVO userVO=new UserVO();
            userVO.setAddress(userDO.getAddress());
            userVO.setAvatar(userDO.getAvatar());
            userVO.setNickname(userDO.getNickname());
            if(userDO.getSex()){
                userVO.setSex("man");
            }else{
                userVO.setSex("woman");
            }
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            Date birthday=userDO.getBirthday();
            userVO.setBirthday(sdf.format(birthday));
            model.addAttribute("userVO",userVO);
            return "person";
        }catch (HttpClientErrorException e){
            return "error";
        }
    }

    /**
     * 更改头像
     * @param avatar
     * @return
     */
    @RequestMapping(value = "updateAvatar" ,method = RequestMethod.POST)
    public String updateAvatar(@RequestParam("avatar")MultipartFile avatar){
        String userId=SSOHelper.getSSOToken(request).getId();
        try{
            if(!"".equals(avatar.getOriginalFilename())){
                File result=new File(userId+".jpg");
                FileOutputStream fileOutputStream=new FileOutputStream(result);
                fileOutputStream.write(avatar.getBytes());
                fileOutputStream.flush();
                fileOutputStream.close();
                FileSystemResource fileSystemResource=new FileSystemResource(result);
                MultiValueMap param1=new LinkedMultiValueMap();
                param1.add("file",fileSystemResource);
                param1.add("filepath","/images/avatar");
                RestTemplate restTemplate=new RestTemplate();
                ResponseEntity<String> responseEntity1=restTemplate.postForEntity(URLConstant.URL_UPLOAD_FILE,param1,String.class);
                String avatarStr=responseEntity1.getBody();

                param1.add("userId",userId);
                ResponseEntity<UserDO> responseEntity=restTemplate.postForEntity(URLConstant.URL_GET_USER_BY_ID,param1,UserDO.class);
                UserDO userDO=responseEntity.getBody();
                userDO.setAvatar(avatarStr);
                param1.add("user",userDO);
                restTemplate.postForEntity(URLConstant.URL_UPDATE_USER,param1,UserDO.class);
            }
        }catch (IOException ioe){

        }catch (HttpClientErrorException hce){

        }
        return redirectTo("showUser");
    }

    /**
     *
     * @param sex
     * @param birthday
     * @param nickname
     * @param address
     * @return
     */
    @RequestMapping(value = "updateUser" ,method = RequestMethod.POST)
    public String updateUser(@RequestParam("sex")int sex,
                             @RequestParam("birthday")String birthday,
                             @RequestParam("nickname")String nickname,
                             @RequestParam("address")String address){
        String userId=SSOHelper.getSSOToken(request).getId();
        RestTemplate restTemplate=new RestTemplate();
        MultiValueMap param1=new LinkedMultiValueMap();
        param1.add("userId",userId);
        ResponseEntity<UserDO> responseEntity=restTemplate.postForEntity(URLConstant.URL_GET_USER_BY_ID,param1,UserDO.class);
        UserDO userDO=responseEntity.getBody();
        userDO.setNickname(nickname);
        userDO.setAddress(address);
        if(sex==1){
            userDO.setSex(true);
        }else {
            userDO.setSex(false);
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        try {
            userDO.setBirthday(sdf.parse(birthday));
        }catch (ParseException e){

        }
        param1.add("user",userDO);
        try {
            restTemplate.postForEntity(URLConstant.URL_UPDATE_USER,param1,UserDO.class);
            return redirectTo("home");
        }catch (HttpClientErrorException e){
            return "error";

        }
    }

    /**
     * 显示当前用户的历史订单（包含当前订单）
     * @param model
     * @return
     */
    @RequestMapping(value = "/showMyOrder",method= RequestMethod.GET)
    public String showMyOrder(Model model)
    {
        SSOToken ssoToken=SSOHelper.getSSOToken(request);

        String url=URLConstant.URL_LIST_ORDERS+ssoToken.getId();
        RestTemplate restTemplate=new RestTemplate();
        ResponseEntity<List> responseEntity=restTemplate.getForEntity(url,List.class);
        if(responseEntity.getBody()==null){
            return "myorder";
        }
        List<MyOrderVo> orderList=new ArrayList<MyOrderVo>();
        for (Object object:responseEntity.getBody()) {
            try {
                JSONObject jsonObject=JSONObject.fromObject(object);
                MyOrderVo myOrderVo=new MyOrderVo();
                Object houseInfo=jsonObject.get("houseInfo");
                String houseId=(String)JSONObject.fromObject(houseInfo).get("houseId");
                Map<String,String> map=new HashMap<String,String>();
                map.put("id",houseId);
                Object house=restTemplate.getForObject(URLConstant.URL_GET_HOUSE,Object.class,map);
                String image=(String)JSONObject.fromObject(house).get("images");
                String houseName=(String)JSONObject.fromObject(house).get("communityName");
                myOrderVo.setHouseName(houseName);
                myOrderVo.setHouseId(houseId);
                myOrderVo.setHouseImage(image);
                myOrderVo.setOrderId((String)jsonObject.get("orderId"));
                myOrderVo.setOrderTime((String)jsonObject.get("createTime"));
                myOrderVo.setPayment((String)jsonObject.get("payment"));
                myOrderVo.setStatus(jsonObject.get("orderStatus").toString());
                orderList.add(myOrderVo);
            }catch (HttpClientErrorException e){
                return "home";
            }
        }
        model.addAttribute("orderList",orderList);
        return "myorder";

    }
}
